﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
using System.Windows.Media.Imaging;

namespace Ku.AppCore.Converter
{
    public class ImageSourceConverter : IValueConverter
    {
        /// <summary>
        /// 转换图片路径 ，
        /// 例如：相对路径=Resources/Images/Bg/2.jpg【不能带/】 绝对路径= E:/Resources/Images/Bg/2.jpg
        /// </summary>
        /// <param name="value"></param>
        /// <param name="targetType"></param>
        /// <param name="parameter"></param>
        /// <param name="culture"></param>
        /// <returns></returns>
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is string path)
            {
                var uriSource = new Uri(path, UriKind.RelativeOrAbsolute);
                // 如果是相对路径，将其转换为绝对路径
                if (!uriSource.IsAbsoluteUri)
                {
                    string absolutePath = Path.GetFullPath(path);
                    if (!File.Exists(absolutePath))
                    {
                        // 文件不存在，返回 null
                        return null;
                    }
                    uriSource = new Uri(absolutePath, UriKind.Absolute);
                }
                else
                {
                    if (!File.Exists(uriSource.LocalPath))
                    {
                        // 文件不存在，返回 null
                        return null;
                    }
                }
                return new BitmapImage(uriSource);
            }
            return null;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}
